package com.apes.scm.masterdata.frame.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.fsm.FsmFlow;
import com.apes.scm.masterdata.frame.model.ConsignmentRule;
import com.apes.scm.masterdata.frame.model.Contacts;
import com.apes.scm.masterdata.frame.model.Contacts;
import com.apes.scm.masterdata.frame.repository.ContactsRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;



@Service("contactsService")
public class contactsService {

    @Autowired
    private ContactsRepository contactsRepository;

    public Contacts save(SimpleRequest request) {
        JSONObject date = request.getJO().getJSONObject("contact");
        PartyRole contact = SpringManager.getBean(PartyRoleRepository.class).findOne(date.getJSONObject("contact").getString("id"));
        String mobileNumber = date.getString("mobileNumber");
        String storeId = date.getString("storeId");
        String note = date.getString("note");
        Contacts contacts = new Contacts();
        contacts.setContact(contact);
        contacts.setMobileNumber(mobileNumber);
        contacts.setStoreId(storeId);
        contacts.setNote(note);
        DomainService domainService = new DomainService();
        domainService.sendSynEvent("event:contacts.save",date);
        return contactsRepository.saveAndFlush(contacts);
    }

    public String delete(SimpleRequest request) {
        DomainService domainService = new DomainService();
        JSONObject date = request.getJO().getJSONObject("contact");
        domainService.sendSynEvent("event:contacts.delete",date);
        String contactId = date.getJSONObject("contact").getString("id");
        String storeId = date.getString("storeId");
        contactsRepository.deleteContactsById(storeId,contactId);
        return "删除成功";
    }

    /**
     * 查询单个数据
     * @param request
     * @return
     */
    public List<Contacts> findByStoreId(SimpleRequest request) {
        String storeId = request.get("storeId");
        List<Contacts> contacts = contactsRepository.findByStoreId(storeId);
        return contacts;
    }
}
